package cn.edu.lingnan.lsqn.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.stereotype.Service;

import cn.cdahua.basic.model.Pager;
import cn.edu.lingnan.lsqn.dao.IColumnDao;
import cn.edu.lingnan.lsqn.dao.IGroupDao;
import cn.edu.lingnan.lsqn.dao.IUserDao;
import cn.edu.lingnan.lsqn.model.Column;
import cn.edu.lingnan.lsqn.model.Group;
import cn.edu.lingnan.lsqn.model.LsqnException;
import cn.edu.lingnan.lsqn.model.User;

@Service("groupService")
public class GroupService implements IGroupService {

	private IGroupDao groupDao;
	private IUserDao userDao;
	private IColumnDao columnDao;

	public IGroupDao getGroup() {
		return groupDao;
	}

	@Inject
	public void setGroup(IGroupDao groupDao) {
		this.groupDao = groupDao;
	}

	public IUserDao getUserDao() {
		return userDao;
	}

	public IGroupDao getGroupDao() {
		return groupDao;
	}

	@Inject
	public void setGroupDao(IGroupDao groupDao) {
		this.groupDao = groupDao;
	}

	public IColumnDao getColumnDao() {
		return columnDao;
	}

	@Inject
	public void setColumnDao(IColumnDao cloumnDao) {
		this.columnDao = cloumnDao;
	}

	@Inject
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	private void addGroupColumn(Group group, int[] c_id) {
		List<Column> columns = columnDao.list();
		Map<Integer, Column> cids = new HashMap<Integer, Column>();
		for (Column c : columns) {
			cids.put(c.getId(), c);
		}
		for (int id : c_id) {
			if (cids.containsKey(id))
				groupDao.addGroupColumn(group, cids.get(id));
		}
	}

	@Override
	public void add(Group group, int[] c_id) {
		if (c_id == null || c_id.length <= 0)
			throw new LsqnException("请设置该组可访问的内容");
		groupDao.add(group);
		addGroupColumn(group, c_id);
	}

	@Override
	public void delete(int id) {
		Pager<User> users = userDao.listUserByGroup(id);
		if (users.getDatas() != null && users.getDatas().size() > 0)
			throw new LsqnException("该组还有用户存在，请先移除用户");
		groupDao.deleteGroupColumn(id);
		groupDao.delete(id);
	}
	@Override
	public void deleteGroupAndGroupUser(int id) {
		groupDao.deleteGroupUsers(id);
		groupDao.deleteGroupColumn(id);
		groupDao.delete(id);
	}

	@Override
	public Group load(int id) {
		return groupDao.load(id);
	}

	@Override
	public void update(Group group, int[] c_id) {
		if (c_id != null && c_id.length > 0) {
			groupDao.deleteGroupColumn(group.getId());
			addGroupColumn(group, c_id);
		}
		groupDao.update(group);
	}

	@Override
	public List<Group> listGroup() {
		return groupDao.list();
	}
}
